'use client';

import React from 'react';
import {
  ComposedChart,
  Area,
  XAxis,
  YAxis,
  ResponsiveContainer,
  Tooltip,
  ReferenceLine,
} from 'recharts';
import { useMarketData } from '../hooks/useMarketData';

interface DepthChartProps {
  symbol: string;
  onPriceClick?: (price: number) => void;
}

interface ChartDataPoint {
  price: number;
  buyDepth: number;
  sellDepth: number;
  type: 'buy' | 'sell';
}

export default function DepthChart({ symbol, onPriceClick }: DepthChartProps) {
  // 使用币安真实数据
  const { orderBook, loading } = useMarketData({
    symbol: symbol.replace('/', ''),  // BTC/USDT -> BTCUSDT
    dataSource: 'binance',
    enableRealtime: true
  });

  // 处理订单簿数据
  const processOrderBookData = () => {
    if (!orderBook || !orderBook.buyOrders || !orderBook.sellOrders) {
      return { chartData: [], midPrice: 0 };
    }

    // 取前15档买单和卖单
    const buyOrders = orderBook.buyOrders.slice(0, 15).reverse(); // 买单从低到高
    const sellOrders = orderBook.sellOrders.slice(0, 15); // 卖单从低到高

    const chartData = [];
    let buyDepth = 0;
    let sellDepth = 0;

    // 处理买单数据（累计深度）
    for (const order of buyOrders) {
      buyDepth += order.amount;
      chartData.push({
        price: order.price,
        buyDepth: buyDepth,
        sellDepth: 0,
        type: 'buy'
      });
    }

    // 处理卖单数据（累计深度）
    for (const order of sellOrders) {
      sellDepth += order.amount;
      chartData.push({
        price: order.price,
        buyDepth: 0,
        sellDepth: sellDepth,
        type: 'sell'
      });
    }

    // 按价格排序
    chartData.sort((a, b) => a.price - b.price);

    // 计算中间价
    const bestBid = buyOrders[buyOrders.length - 1]?.price || 0;
    const bestAsk = sellOrders[0]?.price || 0;
    const midPrice = (bestBid + bestAsk) / 2;

    return { chartData, midPrice };
  };

  const { chartData, midPrice } = processOrderBookData();

  // 自定义提示框
  const CustomTooltip = ({ active, payload }: { 
    active?: boolean; 
    payload?: Array<{ payload: ChartDataPoint }>; 
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg p-3 shadow-lg">
          <p className="font-medium text-gray-900 dark:text-white">
            价格: ${data.price.toFixed(2)}
          </p>
          {data.buyDepth > 0 && (
            <p className="text-green-600 dark:text-green-400">
              买单深度: {data.buyDepth.toFixed(4)}
            </p>
          )}
          {data.sellDepth > 0 && (
            <p className="text-red-600 dark:text-red-400">
              卖单深度: {data.sellDepth.toFixed(4)}
            </p>
          )}
        </div>
      );
    }
    return null;
  };

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="flex items-center space-x-2 text-gray-600 dark:text-gray-400">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
          <span>加载深度数据...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col">
      {/* 标题栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <h3 className="font-semibold text-gray-900 dark:text-white">市场深度</h3>
        <div className="text-sm text-gray-600 dark:text-gray-400">
          中间价: ${midPrice.toFixed(2)}
        </div>
      </div>

      {/* 图表内容 */}
      <div className="flex-1 p-4">
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart
            data={chartData}
            margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
            onClick={(data) => {
              if (data && data.activePayload) {
                const price = data.activePayload[0]?.payload?.price;
                if (price && onPriceClick) {
                  onPriceClick(price);
                }
              }
            }}
          >
            <XAxis 
              dataKey="price" 
              axisLine={false}
              tickLine={false}
              tick={{ fontSize: 12, fill: '#666' }}
              domain={['dataMin', 'dataMax']}
            />
            <YAxis 
              axisLine={false}
              tickLine={false}
              tick={{ fontSize: 12, fill: '#666' }}
              width={60}
            />
            <Tooltip content={<CustomTooltip />} />
            
            {/* 中间价参考线 */}
            {midPrice > 0 && (
              <ReferenceLine 
                x={midPrice} 
                stroke="#666" 
                strokeDasharray="2 2"
                label={{ value: "中间价", position: "top" }}
              />
            )}
            
            {/* 买单深度区域 */}
            <Area
              type="monotone"
              dataKey="buyDepth"
              stackId="1"
              stroke="#02C076"
              fill="#02C076"
              fillOpacity={0.3}
            />
            
            {/* 卖单深度区域 */}
            <Area
              type="monotone"
              dataKey="sellDepth"
              stackId="2"
              stroke="#F6465D"
              fill="#F6465D"
              fillOpacity={0.3}
            />
          </ComposedChart>
        </ResponsiveContainer>
      </div>

      {/* 图例 */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700">
        <div className="flex items-center justify-center space-x-6 text-xs">
          <div className="flex items-center space-x-1">
            <div className="w-3 h-3 bg-green-500 rounded"></div>
            <span className="text-gray-600 dark:text-gray-400">买单深度</span>
          </div>
          <div className="flex items-center space-x-1">
            <div className="w-3 h-3 bg-red-500 rounded"></div>
            <span className="text-gray-600 dark:text-gray-400">卖单深度</span>
          </div>
          <span className="text-gray-500 dark:text-gray-400">币安实时数据</span>
        </div>
      </div>
    </div>
  );
}
